<?php
/**
 * Copyright (c) 不争网络
 *
 * @Description     个人中心.
 * @Author          Evelyn丶好久不见
 * @Copyright       Copyright (c) 不争网络 保留所有版权()
 * @Date:           2019/4/28
 */
namespace app\api\controller;
use app\common\controller\CommonApi;
use think\Db;
class Order extends CommonApi{
//生成订单
    public function order(){
    	//print_r(json_encode([1,2,3,4,5]));die;
        $type = input('type',1,'intval');
        $address = db('address')->where(['user_id'=>UID,'id'=>input('address',0)])->find();
        if(!$address)
        	$this->apiReturn(0,'地址信息错误');
        do{
            $number = rand(100000000000,999999999999);
            $exists = db('order')->where('number',$number)->find();
        }while($exists);
        if($type == 2){
        //购物车结算
        	$id_arr = json_decode(input('id_arr',''),true);
        	db()->startTrans();
        	$num = 0;$money = 0;
        	foreach ($id_arr as $key => $value) {
        		$car_info = db('shop_car')->where(['id'=>$value])->find();
        		$goodsinfo = db('goods')->where(['id'=>$car_info['goods_id']])->find();
        		if(!$goodsinfo)
        			$this->apiReturn(0,'商品信息错误');
        		if($goodsinfo['surplus_num']<$car_info['num']){
        			$this->apiReturn(0,'库存不足');
        		}
        		$num +=$car_info['num'];
        		$money+=$car_info['num']*$goodsinfo['price'];
        	}

        //生成订单
        	$query[] = db('order')->insert([
        		'user_id'			=>	UID,
        		'number'			=>	$number,
        		'add_time'			=>	time(),
        		'num'				=>	$num,
        		'all_money'			=>	$money,
                'introduce'         =>  input('introduce',''),
        		'address'			=>	input('address')
        	]);
        	$orderinfo = db('order')->field('id,number,all_money,address,add_time,status,introduce')->where(['number'=>$number])->find();
        //添加订单商品
        	foreach ($id_arr as $key => $value) {

        		$car_info = db('shop_car')->where(['id'=>$value])->find();
        		$goodsinfo = db('goods')->where(['id'=>$car_info['goods_id']])->find();
        		if($goodsinfo['surplus_num']<$car_info['num']){
        			$this->apiReturn(0,$goodsinfo['title'].'库存不足');
        		}


        		$query[] = db('order_goods')->insert([
        			'order_id'			=>		$orderinfo['id'],
        			'o_goods_id'		=>		$car_info['goods_id'],
        			'num'				=>		$car_info['num'],
        			'type'				=>		$car_info['type'],
        			'add_time'			=>		time(),
        			'price'				=>		$goodsinfo['price'],
        			'all_price'			=>		$car_info['num']*$goodsinfo['price']
        		]);

        		$query[] = db('goods')->where('id',$car_info['goods_id'])->setDec('surplus_num',$car_info['num']);
                $count = db('shop_car')->where('goods_id',$car_info['goods_id'])->where('num','gt',db('goods')->where('id',$car_info['goods_id'])->value('surplus_num'))->where('status',1)->count();
                if($count>0){
                    $query[] = db('shop_car')->where('goods_id',$car_info['goods_id'])->where('num','gt',db('goods')->where('id',$car_info['goods_id'])->value('surplus_num'))->where('status',1)->update(['status'=>0]);
                }
        	}
        //删除购物车信息
        	$query[] = db('shop_car')->where('id','in',$id_arr)->delete();
        }else{
        	//直接购买
        	$goods = db('goods')->where('id',input('id',0))->find();
        	$goodstype = db('goods_type')->where(['goods_id'=>$goods['id'],'id'=>input('goodstype',0)])->find();
        	if(!$goods || !$goodstype)
        		$this->apiReturn(0,'商品信息错误');
        	$num = input('num',0);
        	if($num<1){
        		$this->apiReturn(0,'数量信息错误');
        	}
        	if($goods['surplus_num']<$num){
        		$this->apiReturn(0,'库存不足');
        	}
        	db()->startTrans();
        	$query[] = db('goods')->where('id',$goods['id'])->setDec('surplus_num',$num);
        	$query[] = db('order')->insert([
        		'user_id'			=>	UID,
        		'number'			=>	$number,
        		'add_time'			=>	time(),
        		'num'				=>	$num,
        		'all_money'			=>	$num*$goods['price'],
                'introduce'         =>  input('introduce',''),
        		'address'			=>	input('address')
        	]);
        	$orderinfo = db('order')->field('id,number,all_money,address,add_time,status,introduce')->where(['number'=>$number])->find();
        	$query[] = db('order_goods')->insert([
        			'order_id'			=>		$orderinfo['id'],
        			'o_goods_id'		=>		$goods['id'],
        			'num'				=>		$num,
        			'type'				=>		input('goodstype'),
        			'add_time'			=>		time(),
        			'price'				=>		$goods['price'],
        			'all_price'			=>		$num*$goods['price']
        		]);
            $count = db('shop_car')->where('goods_id',$goods['id'])->where('num','gt',db('goods')->where('id',$goods['id'])->value('surplus_num'))->where('status',1)->count();
            if($count>0){
                $query[] =db('shop_car')->where('goods_id',$goods['id'])->where('num','gt',db('goods')->where('id',$goods['id'])->value('surplus_num'))->where('status',1)->update(['status'=>0]);
            }
        }

        if(in_array(false,$query)){
    		db()->rollback();
    		$this->apiReturn(0,'下单失败');
    	}

    	db()->commit();
        $order_address = db('address')->where('id',$orderinfo['address'])->find();
    	$orderinfo['address'] = $order_address['province'].$order_address['city'].$order_address['county'].$order_address['address'];
    	$orderinfo['add_time'] = date('Y-m-d H:i:s',$orderinfo['add_time']);
    	$goods = db('order_goods')->alias('o')->join('goods g','g.id = o.o_goods_id','left')->field('num,all_price,g.id as goods_id,o.price,banner as image,o.type')->where(['o.order_id'=>$orderinfo['id']])->select();
    	foreach ($goods as $key => $value) {
    		$goods[$key]['image'] = $this->host.explode(',', $value['image'])[0];
    		$goods[$key]['type'] = db('goods_type')->where('id',$value['type'])->value('type');
    	}
    	$orderinfo['goods'] = $goods;


    	$this->apiReturn(1,'操作成功',['order_id'=>$orderinfo]);
    }


//订单列表
    public function orderlist(){
        $status = input('status',10);
        $where = [];
        if($status!=10){
            $where['status'] = ['eq',$status];
        }
        $list = db('order')->field('id,number,status')->where(['user_id'=>UID])->where($where)->order('pay_time desc,add_time desc')->limit(($this->p-1)*10,10)->select();
        foreach ($list as $key => $value) {
            $order_goods = db('order_goods')->alias('og')->join('goods g','g.id = og.o_goods_id','left')->field('o_goods_id,type,og.price,banner as image,all_price,title,num')->where(['order_id'=>$value['id']])->select();
            foreach ($order_goods as $k => $v) {
                $order_goods[$k]['image'] = $this->host.explode(',',$v['image'])[0];
                $order_goods[$k]['type'] = db('goods_type')->where(['id'=>$v['type']])->value('type');
            }
            $list[$key]['goods'] = $order_goods;
            //echo"<pre>";print_r($order_goods);die;
        }

        $this->apiReturn(1,'订单列表',$list);
    }

//订单详情
    public function orderinfo(){
        $id = input('id',0);
        $info = db('order')->field('id,number,status,address,all_money,pay_time,add_time,express,express_num')->where(['id'=>$id])->find();
        if(!$info)
            $this->apiReturn(0,'订单信息错误');
        if($info['add_time']>0){
            $info['add_time'] = date('Y-m-d H:i:s',$info['add_time']);
        }
        if($info['pay_time']>0){
            $info['pay_time'] = date('Y-m-d H:i:s',$info['pay_time']);
        }

    //地址
        $address = db('address')->where(['id'=>$info['address']])->find();

        $goods = db('order_goods')->alias('og')->join('goods g','g.id = og.o_goods_id','left')->field('o_goods_id,type,og.price,banner as image,all_price,title,num')->where(['order_id'=>$id])->select();
        foreach ($goods as $key => $value) {
            $goods[$key]['image'] = $this->host.explode(',',$value['image'])[0];
            $goods[$key]['type'] = db('goods_type')->where(['id'=>$value['type']])->value('type');
        }
        $info['goods'] = $goods;
        $info['address'] = [];
        $info['address']['address'] = $address['province'].$address['city'].$address['county'].$address['address'];
        $info['address']['name'] = $address['name'];
        $info['address']['phone'] = $address['phone'];
        $this->apiReturn(1,'订单详情',$info);
    }

//确认收货
    public function orderok(){
        $id = input('id',0);
        $info = db('order')->where(['id'=>$id,'user_id'=>UID])->find();
        if(!$info)
            $this->apiReturn(0,'订单信息错误');
        if($info['status']>2){
            $this->apiReturn(0,'订单已完成');
        }
        $query = db('order')->where(['id'=>$id])->update(['status'=>3]);
        if(!$query)
            $this->apiReturn(0,'操作失败');
        $this->apiReturn(1,'操作成功');
    }

//取消订单
    public function ordercancel(){
        $id = input('id',0);
        $info = db('order')->where(['id'=>$id,'user_id'=>UID])->find();
        if(!$info)
            $this->apiReturn(0,'订单信息错误');
        if($info['status']>0){
            $this->apiReturn(0,'订单已支付，退款请联系客户');
        }
        $query = db('order')->where(['id'=>$id])->update(['status'=>5]);
        if(!$query)
            $this->apiReturn(0,'操作失败');
        $this->apiReturn(1,'操作成功');
    }

//订单评价
    public function evaluate(){
        $order = input('id',0);
        $info = db('order')->where(['id'=>$order,'user_id'=>UID])->find();
        if(!$info)
            $this->apiReturn(0,'订单信息错误');
        if($info['status']!=3){
            $this->apiReturn(0,'订单未收货');
        }
        
        $arr = json_decode($this->post['commit'],true);
        
        db()->startTrans();
        foreach ($arr as $key => $value) {
            $data = [];
            $data['goods_id'] = $value['goods_id'];
            $data['stars']    = $value['star'];
            $data['content'] = $value['content'];
            $data['image'] =    $value['image'];
            
            
            $data['user_id'] = UID;
            $data['order_id'] = $order;
            $query[] = db('evaluate')->insert($data);
        }
        $query[] = db('order')->where(['id'=>$order,'user_id'=>UID])->update(['status'=>4]);
        if(in_array(false,$query)){
            db()->rollback();
            $this->apiReturn(0,'评价失败');
        }
        db()->commit();
        $this->apiReturn(1,'评价成功');

    }
}